"""
上报接口数据模型
"""
from dataclasses import dataclass, field, asdict
from typing import List, Dict, Any, Optional
import time
import uuid
import random

# 应用ID常量
APPLICATION_ID = "1740158337424"

# 页面名称列表
PAGE_NAMES = [
    "AskFragment",
    "StockV2Fragment",
    "SellV2Fragment",
    "RentMarketV2Fragment",
    "MarketV2Fragment",
    "HomePageV2Fragment",
    "UserFragmentV3",
    "首页"
]

@dataclass
class PageViewData:
    """页面访问数据"""
    timestamp: int
    begin: bool = True

@dataclass
class EventData:
    """事件数据"""
    attributes: Dict[str, Any] = field(default_factory=dict)

@dataclass
class LogData:
    """日志数据"""
    pv: Optional[PageViewData] = None
    event: Optional[EventData] = None

@dataclass
class TrackLog:
    """追踪日志"""
    deviceId: str
    userId: str
    pageName: str
    actionTime: int
    bcn: str = "UU898"
    eventId: str = ""
    pageId: str = ""
    uniquePageId: str = ""
    preUniquePageId: str = ""
    applicationId: str = APPLICATION_ID
    logId: str = field(default_factory=lambda: str(uuid.uuid4()))
    data: LogData = field(default_factory=LogData)

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式
        
        Returns:
            Dict[str, Any]: 字典格式的数据
        """
        result = asdict(self)
        # 只保留非None的data字段
        if self.data:
            data_dict = {}
            if self.data.pv:
                data_dict["pv"] = asdict(self.data.pv)
            if self.data.event:
                data_dict["event"] = asdict(self.data.event)
            result["data"] = data_dict
        return result

@dataclass
class TrackReportRequest:
    """上报请求数据"""
    logList: List[TrackLog]
    Sessionid: str

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式
        
        Returns:
            Dict[str, Any]: 字典格式的数据
        """
        return {
            "logList": [log.to_dict() for log in self.logList],
            "Sessionid": self.Sessionid
        }

def generate_past_timestamp(minutes: int = 5) -> int:
    """生成过去指定分钟内的随机时间戳
    
    Args:
        minutes: 过去多少分钟内，默认5分钟
        
    Returns:
        int: 毫秒时间戳
    """
    now = time.time()
    past = now - minutes * 60
    random_time = random.uniform(past, now)
    return int(random_time * 1000)

def create_page_view_log(device_id: str, user_id: str, page_name: str, 
                        begin: bool = True, timestamp: int = None) -> TrackLog:
    """创建页面访问日志
    
    Args:
        device_id: 设备ID
        user_id: 用户ID
        page_name: 页面名称
        begin: 是否是开始访问，默认True
        timestamp: 时间戳，默认为None
        
    Returns:
        TrackLog: 页面访问日志
    """
    if timestamp is None:
        timestamp = generate_past_timestamp()
    return TrackLog(
        deviceId=device_id,
        userId=user_id,
        pageName=page_name,
        actionTime=timestamp,
        data=LogData(
            pv=PageViewData(timestamp=timestamp, begin=begin)
        )
    )

def create_event_log(device_id: str, user_id: str, page_name: str,
                    event_id: str, attributes: Dict[str, Any], timestamp: int = None) -> TrackLog:
    """创建事件日志
    
    Args:
        device_id: 设备ID
        user_id: 用户ID
        page_name: 页面名称
        event_id: 事件ID
        attributes: 事件属性
        timestamp: 时间戳，默认为None
        
    Returns:
        TrackLog: 事件日志
    """
    if timestamp is None:
        timestamp = generate_past_timestamp()
    return TrackLog(
        deviceId=device_id,
        userId=user_id,
        pageName=page_name,
        eventId=event_id,
        actionTime=timestamp,
        data=LogData(
            event=EventData(attributes=attributes)
        )
    )

def generate_random_logs(device_id: str, user_id: str, count: int = None) -> List[TrackLog]:
    """生成随机日志列表
    
    Args:
        device_id: 设备ID
        user_id: 用户ID
        count: 生成数量，如果不指定则随机1-5个
        
    Returns:
        List[TrackLog]: 日志列表
    """
    if count is None:
        count = random.randint(1, 5)
        
    # 随机选择页面
    selected_pages = random.sample(PAGE_NAMES, min(count, len(PAGE_NAMES)))
    
    logs = []
    for page_name in selected_pages:
        # 生成一致的时间戳
        timestamp = generate_past_timestamp()
        # 随机决定是否为事件日志
        if random.random() < 0.2:  # 20%概率生成事件日志
            log = create_event_log(
                device_id=device_id,
                user_id=user_id,
                page_name=page_name,
                event_id=f"{page_name.lower()}_event",
                attributes={"deviceType": "android"},
                timestamp=timestamp
            )
        else:  # 80%概率生成页面访问日志
            log = create_page_view_log(
                device_id=device_id,
                user_id=user_id,
                page_name=page_name,
                begin=random.choice([True, False]),
                timestamp=timestamp
            )
        logs.append(log)
    
    return logs